import { Component, OnInit, Input, OnDestroy } from '@angular/core'
import { ChargeBackDataService } from '../../../charge-back.data.service'
import { Observable } from 'rxjs'
import { CurrencyService } from '@shared/services/currency.service'
import { IOption } from '@shared/interfaces/common'
import { HelperService } from '@shared/services/helper.service'
import { ReasonCodeMap } from '@shared/interfaces/operation'
import { numScale } from 'app/utils/helpers'
import { I18NService } from '@core'
import { take } from 'rxjs/operators'

@Component({
  selector: 'app-charge-back-representment-operate',
  templateUrl: './representment-operate.component.html',
})
export class RepresentmentOperateComponent implements OnInit, OnDestroy {
  @Input() currency: string
  /** 是否是美运的交易 */
  @Input() isAmex: boolean
  /** 金额 */
  @Input() transAmt: number
  decimal$: Observable<number>
  reasonCodeOptions: IOption[]

  constructor(
    public chargeBackDataService: ChargeBackDataService,
    private currencyService: CurrencyService,
    private helperService: HelperService,
    private i18n: I18NService,
  ) {}

  ngOnInit() {
    this.decimal$ = this.currencyService.getDecimalByCode(this.currency).pipe(take(1))
    this.reasonCodeOptions = this.genReasonCodeOptions()
    this.chargeBackDataService.operateBody.amt = this.transAmt
    this.parseAmt()
  }

  ngOnDestroy() {
    this.chargeBackDataService.resetOperateBody()
  }

  genReasonCodeOptions(): IOption[] {
    if (!this.isAmex) {
      return []
    }
    return this.helperService.generateOptionsFromEnum(ReasonCodeMap)
  }

  parseAmt(): void {
    this.decimal$.subscribe(val => {
      if (val === 2) {
        this.transAmt = numScale(this.transAmt, -2)
        this.chargeBackDataService.operateBody.amt = this.transAmt
      }
    })
  }

  searchReasonCode(val: string) {
    this.reasonCodeOptions = !val
      ? this.genReasonCodeOptions()
      : this.genReasonCodeOptions().filter(
          code =>
            code.label.toLocaleLowerCase().includes(val.toLocaleLowerCase()) ||
            code.value
              .toString()
              .toLocaleLowerCase()
              .includes(val.toLocaleLowerCase()),
        )
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
